package com.atguigu.pojo;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.List;

public class Dom4jTest {
    @Test
    public void test1() throws Exception {
        //创建一个SAXReader输入流，去读取xml配置文件，生成Document对象
        SAXReader saxReader=new SAXReader();

        try {
            Document document = saxReader.read("src/books.xml");
            System.out.println(document);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test2() throws Exception {
        //1.读取books.xml文件
        SAXReader reader=new SAXReader();
        //在junit测试中，相对路径是从模块名开始算的
        Document document= reader.read("src/books.xml");
        //2.通过文档对象获取根元素
        Element rootElement=document.getRootElement();
//        System.out.println(rootElement);

        List<Element> books = rootElement.elements("book");
        //4.遍历，处理每个book标签转换为Book类
        for(Element book:books){
            //asXML()把标签对象转换为标签字符串
//            System.out.println(book.asXML());
            Element nameElement=book.element("name");
//            System.out.println(nameElement.asXML());
            //getText方法可以获取标签中的文本内容
            String nameText=nameElement.getText();
//            System.out.println(nameText);

            //直接获取指定标签名的文本内容
            String  priceText = book.elementText("price");
            String authorText = book.elementText("author");
//            System.out.println(authorText);
//            System.out.println(priceText);

            //获取属性值
            String snValue = book.attributeValue("sn");
//            System.out.println(snValue);

            System.out.println(new Book(snValue,nameText,Double.parseDouble(priceText),authorText));
        }
    }

}
